﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace DynamicText.Components.Presenters
{
    using System.Reflection;
    using System.Web.UI;

    using DotNetNuke.Common.Utilities;

    using DynamicText.Components.Controller;
    using DynamicText.Components.Views;

    using YourCompany.Modules.DynamicText;

    public class ViewDynamicTextPresenter
    {
        #region "Private Memebers"
        private IViewDynamicText View;
        private IDynamicTextController Controller;
        #endregion


        public ViewDynamicTextPresenter(IViewDynamicText _View, IDynamicTextController _Controller)
        {
            View = _View;
            Controller = _Controller;
        }

        public void OnViewLoad()
        {
            try
            {
                List<DynamicTextInfo> colDynamicTexts = null;

                // get the content from the DynamicText table
                colDynamicTexts = Controller.GetDynamicTexts(View.ModuleId);

                if (colDynamicTexts.Count == 0)
                {
                    // add the content to the DynamicText table
                    DynamicTextInfo objDynamicText = new DynamicTextInfo();
                    objDynamicText.ModuleId = View.ModuleId;
                    objDynamicText.Content = "View.Content";
                    objDynamicText.CreatedByUser = View.UserId;
                    Controller.AddDynamicText(objDynamicText);
                    colDynamicTexts.Add(objDynamicText);
                }
                // bind the content to the repeater
                View.colDynamicTexts = colDynamicTexts;
            }
            catch (Exception exc)
            {
                View.Exception = exc;
            }
        }

        public string PrepareCurrentRow(DynamicTextInfo _DynamicTextInfo)
        {
            string strContent = "";

            // add content to template
            if (!string.IsNullOrEmpty(Convert.ToString(View.Settings["template"])))
            {
                strContent = Convert.ToString(View.Settings["template"]);
            }
            Dictionary<string, PropertyInfo> objProperties = CBO.GetProperties<DynamicTextInfo>();
            PropertyInfo objPropertyInfo = default(PropertyInfo);
            foreach (string key in objProperties.Keys)
            {
                objPropertyInfo = (PropertyInfo)objProperties[key];
                strContent = strContent.Replace("[" + objPropertyInfo.Name.ToUpper() + "]", DataBinder.Eval(_DynamicTextInfo, objPropertyInfo.Name).ToString());
            }
            return strContent;
        }

    }
}